package event.money.tracker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import MTClient.ClientLogic;
import SQLManager.SQLManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EventDetails extends Activity {
	
	final static int DIALOG_PRODUCT = 0x10;
	final static int DIALOG_DEBT = 0x100;
	
	private Integer selected_product = null;
	
	private Integer eventID = null;
	private Integer eventIDserver = null;
	private SimpleIDAdapter product_adapter = null;
	private Integer eventTerminated = 0;
	
	private ProgressDialog loadingpopup = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	
	    setContentView(R.layout.event_details);
	    
	    // set current activity (need this for callback)
        ClientLogic.SetCurrentActivity(this);

	    eventID = getIntent().getExtras().getInt("eventID");
	    
	    // get event
	    
	    SQLManager.GetInstance().open();
  		Cursor EventListCur = SQLManager.GetInstance().FetchEventInfoWithID(eventID.toString());
  		if (EventListCur.getCount() == 1) {
  			
  			EventListCur.moveToFirst();
  			
  			((TextView)findViewById(R.id.EventDetailsTitle)).setText(EventListCur.getString(EventListCur.getColumnIndex("Title")));
  			((TextView)findViewById(R.id.EventDetailsDescr)).setText(EventListCur.getString(EventListCur.getColumnIndex("Location")));

  			eventTerminated = EventListCur.getInt(EventListCur.getColumnIndex("IsTerminated"));
  			eventIDserver = EventListCur.getInt(EventListCur.getColumnIndex("EventID"));
  		}
  		
  		Button TerminateDebtBTN =(Button)findViewById(R.id.EventDetails_ShowMembers);
  		
  		Button AddproductBTN =(Button)findViewById(R.id.EventDetailsAddProduct);
	    AddproductBTN.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(getApplicationContext(), AddProduct.class);
		        intent.putExtra("eventID", eventID);
		        startActivityForResult(intent, 0);
			}
		});
  		
  		if(eventTerminated != 0) {
  			
  			TerminateDebtBTN.setText("Show Debts");
  			
  			AddproductBTN.setEnabled(false);
  			
  			TerminateDebtBTN.setOnClickListener(new View.OnClickListener() {
  				@Override
  				public void onClick(View v) {
  					
  					showDialog(DIALOG_DEBT);
  				}
  			});
  			
  		} else {
  			
  			TerminateDebtBTN.setText("Close Event");
  			TerminateDebtBTN.setOnClickListener(new View.OnClickListener() {
  				@Override
  				public void onClick(View v) {
  					
  					// loading popup
  					loadingpopup = ProgressDialog.show(EventDetails.this, "", 
  			                "Loading. Please wait...", true);
  					
  					// send request
  					ClientLogic.GetInstance().SendStackTakeEventRequest(eventIDserver.toString());
  				}
  			});
  			
  		}
	    
  		populate_productlist();
	    
	    
	    Button CancelBTN =(Button)findViewById(R.id.EventDetails_Cancel);
	    CancelBTN.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(RESULT_OK);
		    	finish();
			}
		});
	}
	
	public void handle_terminate_result(boolean success) {
    	
    	loadingpopup.dismiss();
    	
    	if(success)
    		this.runOnUiThread(new Runnable() {
    		    public void run() {
    		    	Toast.makeText(EventDetails.this.getApplicationContext(), "Event has been successfully closed!",
    	    	            Toast.LENGTH_LONG).show(); 
    		    	
    		    	eventTerminated = 1;
    		    	
    		    	Button AddproductBTN =(Button)findViewById(R.id.EventDetailsAddProduct);
    		    	AddproductBTN.setEnabled(false);
    		    	
    		    	Button TerminateDebtBTN =(Button)findViewById(R.id.EventDetails_ShowMembers);
    		    	TerminateDebtBTN.setText("Show Debts");
    		    	
    		    	TerminateDebtBTN.setOnClickListener(new View.OnClickListener() {
    	  				@Override
    	  				public void onClick(View v) {
    	  					
    	  					showDialog(DIALOG_DEBT);
    	  					
    	  				}
    	  			});
    		    }
    		});
    	else
    		this.runOnUiThread(new Runnable() {
    		    public void run() {
    		    	Toast.makeText(EventDetails.this.getApplicationContext(), "Error while closing the event! All users synchronized?",
    	    	            Toast.LENGTH_LONG).show(); 
    		    }
    		});
    	
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        // redraw products
        populate_productlist();

    }
	
	public void populate_productlist(){
		
		// get products and populate list view
	    
	    ArrayList<Map<String, String>> products = new ArrayList<Map<String, String>>();

	    String[] from = { "ProductTitle", "ProductSubtitle" };  
        int[] to = { R.id.EventItemTitle, R.id.EventItemSubtitle };  
  		
        ArrayList<Integer> idList = new ArrayList<Integer>();

  		SQLManager.GetInstance().open();
  		Cursor ProductListCur = SQLManager.GetInstance().FetchProductList(eventID.toString());
  		if (ProductListCur.getCount() > 0) {
  			while (ProductListCur.moveToNext()){
  				
  				Map<String, String> product_item = new HashMap<String, String>();
  				product_item.put("ProductTitle", ProductListCur.getString(ProductListCur.getColumnIndex("ProductName")));
  				product_item.put("ProductSubtitle", "Owner: " + ClientLogic.GetInstance().GetUserNameFromID(ProductListCur.getString(ProductListCur.getColumnIndex("Owner"))) + "	Price: " + ProductListCur.getString(ProductListCur.getColumnIndex("Price")) );
  				products.add(product_item);
  				
  				idList.add(ProductListCur.getInt(ProductListCur.getColumnIndex("ID")));
  			}
  				
  		}	    
  		
  		ListView lv = (ListView)findViewById(R.id.EventProductsList);
  		
  		product_adapter = new SimpleIDAdapter(this, products, idList, R.layout.event_items, from, to);
	    
  		lv.setAdapter(product_adapter);
	    
	    lv.setTextFilterEnabled(true);

	    lv.setOnItemClickListener(new OnItemClickListener() {
	      public void onItemClick(AdapterView<?> parent, View view,
	          int position, long id) {
	    	  
	    	  selected_product = product_adapter.GetUniqueID(position);
	    	  showDialog(DIALOG_PRODUCT);
	        
	      }
	    });
		
	}
	
	@Override
	protected Dialog onCreateDialog (int dialog_id) {
		
		Context mContext = this;
        Dialog dialog = new Dialog(mContext);
		
		switch(dialog_id){
		
		case DIALOG_PRODUCT:
			 // look up data from local db
	        String product_descr = "";
	        String product_name = "";
	        
	        SQLManager.GetInstance().open();
	  		Cursor ProductListCur = SQLManager.GetInstance().FetchProductItem(eventID.toString(), selected_product.toString());
	  		if (ProductListCur.getCount() == 1) {
	  			ProductListCur.moveToFirst();
	  					  				
	  			product_descr = ProductListCur.getString(ProductListCur.getColumnIndex("Description"));	  
	  			product_name = ProductListCur.getString(ProductListCur.getColumnIndex("ProductName"));	  
	  		}	    

	
	        dialog.setContentView(R.layout.product_details);
	        dialog.setTitle(product_name);
	
	        TextView text = (TextView) dialog.findViewById(R.id.ProductDetailDesc);
	        text.setText(product_descr);
	        
	        break;
		case DIALOG_DEBT:
			
			// popup window with debt overview
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Debt Overview");
			
			List<String> debtList = new ArrayList<String>();
			
	  		SQLManager.GetInstance().open();
	  		Cursor DebtListCur = SQLManager.GetInstance().FetchDebtList(eventID.toString());
	  		if (DebtListCur.getCount() > 0) {
	  			while (DebtListCur.moveToNext()){
	  				
	  				String debtItem = "";
	  				debtItem += ClientLogic.GetInstance().GetUserNameFromID(DebtListCur.getString(DebtListCur.getColumnIndex("Debtor")));
	  				debtItem += " ----> ";
	  				debtItem += ClientLogic.GetInstance().GetUserNameFromID(DebtListCur.getString(DebtListCur.getColumnIndex("Renter")));
	  				debtItem += "	: ";
	  				debtItem+= DebtListCur.getString(DebtListCur.getColumnIndex("Money"));
	  				debtItem += "$ HKD";
	  				debtList.add(debtItem);
	  				
	  			}
	  				
	  		}	 
	  		
			ListView modeList = new ListView(this);
			ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, debtList);
			modeList.setAdapter(modeAdapter);

			builder.setView(modeList);
			dialog = builder.create();
			
			break;
		default:
		}
        
        return dialog;
	}

}
